package com.mjf.cjt.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.mjf.cjt.domain.TFSalesOrder;
import com.mjf.cjt.domain.TFSalesOrderItem;
import com.mjf.cjt.mapper.TFSalesOrderMapper;
import com.mjf.cjt.service.AsyncTMService;
import com.mjf.cjt.service.TFSalesOrderItemService;
import com.mjf.cjt.service.TFSalesOrderService;
import com.mjf.cjt.vo.SaleDeliveryVo;
import com.mjf.cjt.vo.TFSalesOrderResVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/4/24 10:39
 */
@Service
public class TFSalesOrderServiceImpl extends ServiceImpl<TFSalesOrderMapper, TFSalesOrder>
    implements TFSalesOrderService {

    @Autowired
    private TFSalesOrderItemService tfSalesOrderItemService;
    @Autowired
    private AsyncTMService asyncTMService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void asyncSaleDeliveryOrderFromRemote(String start, String end) {
        try {
            List<SaleDeliveryVo> remote = asyncTMService.getSaleDeliveryOrderFromRemote(start, end);
            if (CollectionUtil.isEmpty(remote)) {
                return;
            }
            List<TFSalesOrder> orders = new ArrayList<>();
            List<TFSalesOrderItem> orderItems = new ArrayList<>();
            // 按订单ID分组
            Map<Long, List<SaleDeliveryVo>> map = remote.stream().collect(Collectors.groupingBy(SaleDeliveryVo::getId));
            for (Map.Entry<Long, List<SaleDeliveryVo>> entry : map.entrySet()) {
                SaleDeliveryVo saleDeliveryVo = entry.getValue().get(0);
                TFSalesOrder order = new TFSalesOrder();
                order.setId(saleDeliveryVo.getId());
                order.setOrderNumber(saleDeliveryVo.getCode());
                order.setDepartmentName(saleDeliveryVo.getDepartment_name());
                order.setDepartmentCode(saleDeliveryVo.getDepartment_code());
                if (StrUtil.isNotBlank(saleDeliveryVo.getVoucherdate())) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                    order.setOrderDate(LocalDate.parse(saleDeliveryVo.getVoucherdate().replace("/", "-"), formatter));
                }
                if (StrUtil.isNotBlank(saleDeliveryVo.getVoucherdate())) {
                    order.setCustomerId(Long.parseLong(saleDeliveryVo.getCustomer_id()));
                }
                order.setCustomerCode(saleDeliveryVo.getCustomer_code());
                order.setCustomerName(saleDeliveryVo.getCustomer_name());
                order.setFax(saleDeliveryVo.getCustomer_fax());
//                order.setProjectCode(saleDeliveryVo.getProject_name());
                order.setProjectName(saleDeliveryVo.getProject_name());
                order.setSalerName(saleDeliveryVo.getClerk_name());
                order.setSalerCode(saleDeliveryVo.getClerk_code());
                order.setOrigamount(saleDeliveryVo.getOrigamount());
                order.setPubuserdefnvc2(saleDeliveryVo.getPubuserdefnvc2());
                order.setTimes(LocalDateTime.now());
                orders.add(order);

                for (SaleDeliveryVo item : entry.getValue()) {
                    TFSalesOrderItem orderItem = new TFSalesOrderItem();
                    orderItem.setItemId(item.getSaledeliverydetails_id());
                    orderItem.setOrderId(item.getId());
                    orderItem.setProjectName(item.getProject_name());
                    orderItem.setMaterialCode(item.getSaledeliverydetails_inventory_code());
                    orderItem.setMaterialName(item.getSaledeliverydetails_inventory_name());
                    orderItem.setQuantity(item.getSaledeliverydetails_quantity());
                    orderItem.setUnitPrice(item.getSaledeliverydetails_origdiscountprice());
                    orderItem.setSaleAmount(item.getSaledeliverydetails_origdiscountamount());
                    orderItem.setExpenseamount(item.getSaledeliverydetails_expenseamount());
                    orderItem.setInventoryPriuserdefdecm1(item.getSaledeliverydetails_inventory_priuserdefdecm1());
                    orderItem.setRebateRate(item.getSaledeliverydetails_inventory_priuserdefdecm1());
                    orderItem.setInventoryPriuserdefdecm2(item.getSaledeliverydetails_inventory_priuserdefdecm2());
                    orderItem.setPubuserdefnvc1(item.getSaledeliverydetails_pubuserdefnvc1());
                    orderItem.setTimes(LocalDateTime.now());
                    orderItems.add(orderItem);
                }
            }
            saveOrUpdateBatch(orders);
            tfSalesOrderItemService.saveOrUpdateBatch(orderItems);
        } catch (ChanjetApiException e) {
            throw new RuntimeException(e);
        }
    }
}
